// 数据包做Base64编码，然后添加\r\n
package wirepack

import (
	"bytes"
	"encoding/base64"
)

const BASE64CRLN = "base64crln"

// 分隔符
// const Base64CrLnDelimiter = "\r\n"
const Base64CrLnDelimiter = "\n"

type Base64CrLf struct {
	buf []byte
}

func NewBase64CrLf() *Base64CrLf {
	return &Base64CrLf{
		buf: make([]byte, 0),
	}
}

func (p *Base64CrLf) Protocol() string {
	return BASE64CRLN
}

func (p *Base64CrLf) Pack(buf []byte) []byte {
	str := base64.StdEncoding.EncodeToString(buf)
	return []byte(str + Base64CrLnDelimiter)
}

func (p *Base64CrLf) Decode(data []byte) [][]byte {
	lines := make([][]byte, 0)
	p.buf = ByteSliceCombine(p.buf, data)
	for {
		index := bytes.Index(p.buf, []byte(Base64CrLnDelimiter))
		if index == -1 {
			break
		}
		line, err := base64.StdEncoding.DecodeString(string(p.buf[:index]))
		if err != nil {
			continue
		}
		lines = append(lines, line)
		p.buf = p.buf[index+len(Base64CrLnDelimiter):]
	}
	return lines
}
